package com.thread.sample;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestMainSampleAnalysor {

	public static void main(String[] args) {

		final int MAX_THREADS = 1;
		String fileName = "c:\\";
		String keyword = "666";

		System.out.println("System Starting...");
		long start = new Date().getTime();
		System.out.println("start at: " + start);
//		ExecutorService executor = Executors.newCachedThreadPool();
		ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
		
		CompletionService<AnalyseResult> comp = new ExecutorCompletionService<>(executor);
		
		for (int i = 0; i < 10; i++) {
			FileAnalysorCallable ceator = new FileAnalysorCallable(fileName + i, keyword);
			
			comp.submit(ceator);
		}
		
		executor.shutdown();
		
		Map<String, Integer> map = new HashMap<>();
		
		int index = 0;
		while (index < 10){
			
			Future<AnalyseResult> res =  comp.poll();
			
			if (res == null)
				continue;
			
			index ++;
			
			try {
				AnalyseResult result = res.get();
				
				if (!map.containsKey(result.getKeyword())){
					map.put(result.getKeyword(), result.getNumber());
					continue;
				}
				
				for(String line : result.getLines()){
					System.out.println(line);
				}
				
				map.put(result.getKeyword(), map.get(result.getKeyword()) + result.getNumber());
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		
		//loop the map
		for (String key : map.keySet()) {
			System.out.println("Key:" + key + " Number:" + map.get(key));
		}
		
		long end = new Date().getTime();
		System.out.println("end at: " + end);
		
		System.out.println(MAX_THREADS + " thread(s) total:" + (end - start));
		
		System.out.println("System finished.");
		
	}

}
